package com.apobates.forum.thrones.controller;

import com.apobates.forum.core.ImageIOMeta;
import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.core.entity.proxy.BoardGroupReplica;
import com.apobates.forum.core.entity.proxy.BoardReplica;
import com.apobates.forum.core.entity.proxy.TopicReplica;
import com.apobates.forum.core.service.BoardGroupService;
import com.apobates.forum.core.service.BoardService;
import com.apobates.forum.core.service.PostsService;
import com.apobates.forum.core.service.TopicService;
import com.apobates.forum.thrones.rss.TopicRssItem;
import com.apobates.forum.thrones.rss.TopicRssResult;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * RSS控制器
 *
 * @author xiaofanku
 * @since 20200526
 */
@Controller
@RequestMapping(value = "/rss")
public class RssController {
    @Autowired
    private BoardGroupService boardGroupService;
    @Autowired
    private BoardService boardService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private PostsService postsService;
    @Autowired
    private ImageIOMeta imageIOMeta;
    @Value("${site.pageSize}")
    private int pageSize;
    @Value("${site.domain}")
    private String siteDomain;
    @Value("${site.meta.description}")
    private String descript;
    //中心
    @GetMapping(path = "/")
    public String homePage(HttpServletRequest request, Model model) {
        List<BoardGroupReplica> rs = boardGroupService.getAllUsedAndBoard(false);
        model.addAttribute("rs", rs);
        return "default/rss/index";
    }
    // 动态
    @GetMapping(path = "/recent.xml", produces = "application/xml;charset=UTF-8")
    public ModelAndView recentTopic(HttpServletRequest request, Model model) {
        List<TopicReplica> topices = topicService.getRecentRelateContent(pageSize).stream().sorted(Comparator.comparing(TopicReplica::getRankingDateTime).reversed()).collect(Collectors.toList());
        
        ModelAndView view = new ModelAndView();
        view.setViewName("topicRssView");
        view.addObject("feeds", toRss(topices));
        return view;
    }
    
    // RSS版块
    @GetMapping(path = "/board.xml", produces = "application/xml;charset=UTF-8")
    public ModelAndView rssBoardAction(
            @RequestParam("id") long recordId,
            @RequestParam("volumes") int boardGroupId,
            HttpServletRequest request,
            Model model) {
        BoardReplica board = boardService.get(recordId, boardGroupId).orElseGet(BoardReplica::new);
        List<Topic> topices = topicService.getRecentForBoard(recordId, pageSize).collect(Collectors.toList());
        
        ModelAndView view = new ModelAndView();
        view.setViewName("topicRssView");
        view.addObject("feeds", toRss(board, topices));
        return view;
    }
    
    //RSS话题
    @GetMapping(path = "/topic.xml", produces = "application/xml;charset=UTF-8")
    public ModelAndView rssTopicAction(@RequestParam("id") long recordId, HttpServletRequest request, Model model) {
        TopicReplica topic = topicService.getTopicContentAndStatsForRSS(recordId, imageIOMeta).orElseGet(TopicReplica::new);
        List<Posts> posts = postsService.getRecentForRSS(recordId, pageSize, imageIOMeta, false).collect(Collectors.toList());
        
        ModelAndView view = new ModelAndView();
        view.setViewName("topicRssView");
        view.addObject("feeds", toRss(topic, posts));
        return view;
    }
    
    private TopicRssResult toRss(BoardReplica board, List<Topic> topices) {
        List<TopicRssItem> items = topices.stream().map(t -> new TopicRssItem(
                t.getTitle(),
                String.format("%s/topic/%s.xhtml", siteDomain, TopicReplica.generateConnectString(t.getId(), t.getBoardId(), t.getVolumesId())),
                t.getSummary(),
                t.getEntryDateTime())).collect(Collectors.toList());
        return new TopicRssResult(board.getTitle(), String.format("%s/board/%s.xhtml", siteDomain, board.getConnect()), board.getDescription(), items);
    }
    
    private TopicRssResult toRss(TopicReplica topic, List<Posts> posts) {
        String topicLink = String.format("%s/topic/%s.xhtml", siteDomain, topic.getConnect());
        List<TopicRssItem> items = posts.stream().map(p -> new TopicRssItem(
                "回复:" + topic.getTitle(),
                topicLink + "#posts-" + p.getId(),
                p.getContent(),
                p.getEntryDateTime()
        )).sorted(Comparator.comparing(TopicRssItem::getDate)).collect(Collectors.toList());
        return new TopicRssResult(topic.getTitle(), topicLink, topic.getContent().getContent(), items);
    }
    
    private TopicRssResult toRss(List<TopicReplica> topices) {
        List<TopicRssItem> items = topices.stream().map(t -> new TopicRssItem(
                t.getTitle(),
                String.format("%s/topic/%s.xhtml", siteDomain, t.getConnect()),
                t.getSummary(),
                t.getEntryDateTime())).collect(Collectors.toList());
        return new TopicRssResult("随便看看", siteDomain, descript, items);
    }
}